package handler

import (
	"context"
	"gitee.com/apinktara/cart/common"
	"gitee.com/apinktara/cart/domain/model"
	"gitee.com/apinktara/cart/domain/service"
	. "gitee.com/apinktara/cart/proto/cart"
)

type Cart struct {
	CartDataService service.ICartDataService
}

func (h *Cart) AddCart(ctx context.Context, request *CartInfo, response *ResponseAdd) error {
	cartAdd := &model.Cart{}
	if err := common.SwapTo(request, cartAdd); err != nil {
		return err
	}
	cartID, err := h.CartDataService.AddCart(cartAdd)
	if err != nil {
		return err
	}
	response.CartId = cartID
	return nil
}

func (h *Cart) CleanCart(ctx context.Context, request *Clean, response *Response) error {
	if err := h.CartDataService.CleanCart(request.UserId); err != nil {
		return err
	}
	response.Msg = "success"
	return nil
}

func (h *Cart) Incr(ctx context.Context, request *Item, response *Response) error {
	if err := h.CartDataService.IncrNum(request.Id, request.ChangeNum); err != nil {
		return err
	}
	response.Msg = " incr success"
	return nil
}

func (h *Cart) Decr(ctx context.Context, request *Item, response *Response) error {
	if err := h.CartDataService.DecrNum(request.Id, request.ChangeNum); err != nil {
		return err
	}
	response.Msg = " decr success"
	return nil
}

func (h Cart) DeleteItemByID(ctx context.Context, request *CartID, response *Response) error {
	if err := h.CartDataService.DeleteCart(request.Id); err != nil {
		return err
	}
	response.Msg = " delete cart success"
	return nil
}

func (h Cart) GetAll(ctx context.Context, request *CartFindAll, response *CartAll) error {
	cartAll, err := h.CartDataService.FindAllCart(request.UserId)
	if err != nil {
		return err
	}
	for _, v := range cartAll {
		c := &CartInfo{}
		if err := common.SwapTo(v, c); err != nil {
			return err
		}
		response.CartInfo = append(response.CartInfo, c)
	}
	return nil
}
